package com.lcp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcp.entity.ChronicDisease;
import com.lcp.mapper.ChronicDiseaseMapper;
import com.lcp.service.ChronicDiseaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ChronicDiseaseServiceImpl implements ChronicDiseaseService {

    @Autowired
    private ChronicDiseaseMapper chronicDiseaseMapper;

    @Override
    public ChronicDisease getById(Long id) {
        return chronicDiseaseMapper.selectById(id);
    }

    @Override
    public List<ChronicDisease> listByUserId(Long userId) {
        return chronicDiseaseMapper.selectList(
            new QueryWrapper<ChronicDisease>()
                .eq("user_id", userId)
                .orderByDesc("diagnosis_date")
        );
    }

    @Override
    public ChronicDisease create(ChronicDisease disease) {
        disease.setCreateTime(LocalDateTime.now());
        disease.setUpdateTime(LocalDateTime.now());
        chronicDiseaseMapper.insert(disease);
        return disease;
    }

    @Override
    public ChronicDisease update(ChronicDisease disease) {
        disease.setUpdateTime(LocalDateTime.now());
        chronicDiseaseMapper.updateById(disease);
        return disease;
    }

    @Override
    public void delete(Long id) {
        chronicDiseaseMapper.deleteById(id);
    }

    @Override
    public List<ChronicDisease> listByStatus(Long userId, String status) {
        return chronicDiseaseMapper.selectList(
            new QueryWrapper<ChronicDisease>()
                .eq("user_id", userId)
                .eq("status", status)
                .orderByDesc("diagnosis_date")
        );
    }

    @Override
    public List<ChronicDisease> listUpcomingFollowUps(Long userId) {
        LocalDateTime now = LocalDateTime.now();
        return chronicDiseaseMapper.selectList(
            new QueryWrapper<ChronicDisease>()
                .eq("user_id", userId)
                .ge("next_follow_up_date", now)
                .orderByAsc("next_follow_up_date")
        );
    }

    @Override
    public void updateFollowUpStatus(Long id, String status) {
        ChronicDisease disease = chronicDiseaseMapper.selectById(id);
        if (disease != null) {
            disease.setStatus(status);
            disease.setLastFollowUpDate(LocalDateTime.now());
            disease.setUpdateTime(LocalDateTime.now());
            chronicDiseaseMapper.updateById(disease);
        }
    }
} 